import axios from 'axios';
import { storeToRefs } from 'pinia'; // 用于在组件外访问 store
import { useAuthStore } from '../stores/userStore'; // 确保路径正确
import { ElMessage } from 'element-plus';


const request = axios.create({
  // baseURL: 'http://backend.yzyxw.cpolar.top',
  baseURL: 'http://localhost:8091',
  timeout: 5000,
  withCredentials: true,
});

request.interceptors.request.use(config => {
  const pageKey = config.pageKey || sessionStorage.getItem('pageKey') || '/gamelist';
  const store = useAuthStore();
  const token = store.getToken(pageKey);
  console.log('拦截器 - Page Key:', pageKey);
  console.log('拦截器 - 当前 Token:', token);
  console.log('拦截器 - 请求 URL:', config.url);
  if (config.url !== '/login/login') {
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    } else {
      console.warn('拦截器 - 未找到 Token，可能未登录或 pageKey 不匹配');
    }
  }
  return config;
});

request.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401 && error.config.url !== '/login/login') {
      const store = useAuthStore();
      console.log('Token 无效或过期');
      store.logout(error.config.pageKey || sessionStorage.getItem('pageKey') || '/gamelist');
      ElMessage.error('登录已失效，请重新登录');
      return Promise.reject(new Error('登录已失效，请重新登录'));
    }
    return Promise.reject(error);
  }
);

export default request;